package cn.fanyc.action.blockchain.fbc.browser.controller;

import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Base64;

/**
 * 页面请求控制器
 *
 * @author Fanyc
 * @date 2020-10-18 19:21
 */
@Controller
@RequestMapping("/")
public class HomeUIController {

    /**
     * Fabric网关
     */
    @Autowired
    private Gateway gateway;

    @RequestMapping({"", "/", "/index"})
    public String index(ModelMap modelMap) throws InvalidArgumentException, ProposalException {
        // get the network and contract
        Network network = gateway.getNetwork("mychannel");

        // 获取通道
        Channel channel = network.getChannel();
        // 获取区块高度
        long height = channel.queryBlockchainInfo().getHeight();
        // 获取区块的最新Hash
        String latestHash = Base64.getEncoder().encodeToString(channel.queryBlockchainInfo().getCurrentBlockHash());
        modelMap.addAttribute("height", height);
        modelMap.addAttribute("latestHash", latestHash);
        // 获取当前MSP ID
        modelMap.addAttribute("mspId", gateway.getIdentity().getMspId());
        modelMap.addAttribute("concatCount", channel.getDiscoveredChaincodeNames().size());

        return "index";
    }
}
